package helpers;

/**
 * Reusable code in order to send a message 
 * using udp. It's mainly for sending a message
 * every x amount of seconds. 
 * 
 * This service is used for polling.
 * 
 *  ( ο ω ο )/ hai
 *  
 *  hai \ ( ο ω ο )  
 *  
 * @author psyomn
 */

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.DatagramPacket;

public class SimpleSendMessageService implements Runnable 
{
	/**
	 * Terminate the service by setting to true 
	 */
	private boolean mTerminated = false;
	
	/**
	 * The handle for the socket this service uses
	 */
	private DatagramSocket mSocketHandle; 
	
	/**
	 * Seconds to wait between each transmission 
	 */
	private char mSeconds = 1; 
	
	/**
	 * Hostname to connect to 
	 */
	private String mHostname;
	
	/**
	 * Address to send the message to 
	 */
	private InetAddress mAddress; 
	
	/**
	 * The port to where to send the message
	 */
	private int mPort; 
	
	/**
	 * The constant message to send
	 */
	private String mMessage;
	
	/**
	 * Default constructor
	 */
	public SimpleSendMessageService(String hostname, String message, int port)
	{
		mHostname = hostname; 
		mMessage = message;
		mPort = port; 
		try
    {
	    mAddress = InetAddress.getByName(mHostname);
	    mSocketHandle = new DatagramSocket();
    } 
		catch (Exception e)
    {
	    e.printStackTrace();
    }
	}
	
	/**
	 * Main operation; every whatever seconds it sends the wanted message
	 */
	@Override
  public void run()
  {
		DatagramPacket p; 
		byte[] b = new byte[mMessage.length()]; 
		
		System.out.println("SSMS service started");
		
		/* Do sending here */
	  while (!mTerminated)
	  {
	  	try
	  	{
	  		// Prep message
	  		b = mMessage.getBytes();
	  		
	  		System.out.println("SSMS SSMS : " + new String(b));
	  		
	  		p = new DatagramPacket(b, b.length, mAddress, mPort);
	  		
	  		System.out.println(this.getClass().getName() 
	  				+ " : "
	  				+ " Sending message : " 
	  				+ new String(b) );
	  		
	  		// Send
	  		mSocketHandle.send(p);
	  		
	  		// Be lazy, sleep
	  		Thread.sleep(mSeconds*1000);
	  	}
	  	catch(Exception e)
	  	{
	  		e.printStackTrace();
	  	}
	  }
  }
	
	/**
	 * Getter for the message variable 
	 * @return the string message
	 */
	public String getMessage()
	{
		return mMessage; 
	}
	
	/**
	 * Set the message variable
	 * @param m is the message to send over time
	 */
	public void setMessage(String m)
	{
		mMessage = m; 
	}
	
	public void terminate()
	{
		mTerminated = true; 
	}
}
